package org.dev.biz_search

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.RelativeLayout
import android.widget.SearchView
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.alibaba.android.arouter.facade.annotation.Route
import kotlinx.android.synthetic.main.activity_search.*
import org.dev.`as`.project.common.ui.component.HiBaseActivity
import org.dev.biz_search.SearchViewModel.Companion.PAGE_INIT_INDEX
import org.dev.biz_search.views.GoodsSearchView
import org.dev.biz_search.views.HistorySearchView
import org.dev.biz_search.views.QuickSearchView
import org.dev.hi.hiui.empty.EmptyView
import org.dev.hi.hiui.search.HiSearchView
import org.dev.hi.hiui.search.SimpleTextWatcher
import org.dev.hi.library.util.HiDisPlayUtils
import org.dev.hi.library.util.HiRes
import org.dev.hi.library.util.HiStatusBar

/**
 * Author WenPing
 * CreateTime 2021/8/25.
 * Description:search页面
 */
@Route(path = "search/main")
class SearchActivity : HiBaseActivity() {
    private lateinit var viewModel: SearchViewModel
    private lateinit var searchButton: Button
    private lateinit var searchView: HiSearchView
    private var emptyView: EmptyView? = null
    private var goodsSearchView: GoodsSearchView? = null
    private var quickSearchView: QuickSearchView? = null
    private var historyView: HistorySearchView? = null

    private var status = -1

    companion object {
        const val STATUS_EMPTY = 0
        const val STATUS_HISTORY = 1
        const val STATUS_QUICK_SEARCH = 2
        const val STATUS_GOODS_SEARCH = 3
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        HiStatusBar.setStatusBar(this, true, translucent = false)
        setContentView(R.layout.activity_search)

        viewModel = ViewModelProvider(this)[SearchViewModel::class.java]
        initTopBar()
        updateViewStatus(STATUS_EMPTY)
        queryLocalHistory()
    }

    private fun queryLocalHistory() {
        viewModel.queryLocalHistory()
            .observe(this, Observer { histories ->
                if (histories != null) {
                    // 更新历史数据
                    updateViewStatus(STATUS_HISTORY)
                    historyView?.bindData(histories)
                } else {
                    searchView.editText?.requestFocus()
                }
            })
    }

    private fun updateViewStatus(newStatus: Int) {
        if (status == newStatus) return
        status = newStatus

        var showView: View? = null
        when (status) {
            STATUS_EMPTY -> {
                if (emptyView == null) {
                    emptyView = EmptyView(this)
                    emptyView?.run {
                        setDesc(HiRes.getString(R.string.list_empty_desc))
                        setIcon(R.string.list_empty)
                    }
                }
                showView = emptyView
            }
            STATUS_QUICK_SEARCH -> {
                if (quickSearchView == null) {
                    quickSearchView = QuickSearchView(this)
                }
                showView = quickSearchView
            }
            STATUS_GOODS_SEARCH -> {
                if (goodsSearchView == null) {
                    goodsSearchView = GoodsSearchView(this)
                    goodsSearchView?.enableLoadingMore({
                        val keyWord = searchView.getKeywrod()
                        if (TextUtils.isEmpty(keyWord)) return@enableLoadingMore

                        viewModel.goodsSearch(keyWord!!, false)
                    }, 5)

                }
                showView = goodsSearchView
            }
            STATUS_HISTORY -> {
                if (historyView == null) {
                    historyView = HistorySearchView(this)
                    historyView!!.setOnCheckChangedListener { keyword ->
                        doKeyWordSearch(keyword)
                    }
                    historyView!!.setOnHistoryClearListener {
                        viewModel.clearHistory()
                        updateViewStatus(STATUS_EMPTY)
                    }
                }
                showView = historyView
            }
        }

        if (showView != null) {
            // showView如果没被添加,它的parent是空的
            if (showView.parent == null) {
                container.addView(showView)
            }
            val childCount = container.childCount
            for (index in 0 until childCount) {
                val child = container.getChildAt(index)
                child.visibility = if (child == showView) View.VISIBLE else View.GONE
            }
        }

    }

    private fun doKeyWordSearch(keyword: KeyWord) {
        // 1.搜索框高亮 搜索词
        searchView.setKeyWord(keyword.keyWord, updateHistoryListener)
        // 2.keyword 存储起来
        viewModel.saveHistory(keyword)
        // 3.发起goodsSearch
        val kwClearIconView: View? = searchView.findViewById<View>(R.id.id_search_clear_icon)
        kwClearIconView?.isEnabled = false
        viewModel.goodsSearch(keyword.keyWord, true)
        // bugfix,每次搜索都会执行到这里,执行一次 addObServer;所以进行过滤
        // 如果当前的livedata没有监听者,在这里进行监听
        if (!viewModel.goodsSearchLiveData.hasObservers()) {
            viewModel.goodsSearchLiveData.observe(this, Observer { goodsList ->
                kwClearIconView?.isEnabled = true
                goodsSearchView?.loadFinished(!goodsList.isNullOrEmpty())
                // 如果viewMode的index 是 PAGE_INIT_INDEX 说明还没分页,还在第一次请求
                val loadInit = viewModel.pageIndex == PAGE_INIT_INDEX
                if (goodsList.isNullOrEmpty()) {
                    if (loadInit) {
                        updateViewStatus(STATUS_EMPTY)
                    }
                } else {
                    updateViewStatus(STATUS_GOODS_SEARCH)
                    goodsSearchView?.bindData(goodsList, loadInit)
                }
            })
        }
    }

    private fun initTopBar() {
        nav_bar.setNavListener(View.OnClickListener { onBackPressed() })
        searchButton =
            nav_bar.addRightTextButton(R.string.nav_item_search, R.id.id_nav_item_search)
        searchButton.apply {
            setTextColor(HiRes.getColorStateList(R.color.color_nav_item_search))
            setOnClickListener(searchClickListener)
            isEnabled = false
        }
        searchView = HiSearchView(this)
        searchView.apply {
            layoutParams = RelativeLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                HiDisPlayUtils.dp2px(38f)
            )
            setHintText(HiRes.getString(R.string.search_hint))
            setClearIconClickListener(updateHistoryListener)
            setDebounceTextChangedListener(debounceTextWatcher)
        }
        nav_bar.setCenterView(searchView)
    }

    private val searchClickListener = View.OnClickListener {
        val keyword = searchView.editText?.text?.trim().toString()
        if (TextUtils.isEmpty(keyword)) return@OnClickListener

        doKeyWordSearch(KeyWord(null, keyword))
    }

    private val updateHistoryListener = View.OnClickListener {
        if (viewModel.keywords.isNullOrEmpty()) {
            updateViewStatus(STATUS_EMPTY)
        } else {
            updateViewStatus(STATUS_HISTORY)
            historyView?.bindData(viewModel.keywords)
        }
    }

    private val debounceTextWatcher = object : SimpleTextWatcher() {
        override fun afterTextChanged(s: Editable?) {
            // 在填写入文字后,进行搜索
            val hasContent = s != null && s.trim().trim().isNotEmpty()
            searchButton.isEnabled = hasContent
            if (hasContent) {
                // 快速搜索,并更新
                viewModel.quickSearch(s.toString())
                    .observe(this@SearchActivity, Observer { keywords ->
                        if (keywords!!.isNotEmpty()) {
                            updateViewStatus(STATUS_EMPTY)
                        } else {
                            updateViewStatus(STATUS_QUICK_SEARCH)
                            quickSearchView?.bindData(keywords, {
                                doKeyWordSearch(it)
                            })
                        }
                    });

            } else {
                updateHistoryListener.onClick(null)
            }
        }
    }
}































